//
//  AppConfig.m
//  MapLink
//
//  Created by meng on 5/22/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "AppConfig.h"


@implementation AppConfig
@synthesize propDict;

- (BOOL) firstTime {
	
	if (propDict)
		return NO;
	
	NSString *finalPath = [NSString stringWithString:[self getConfigFile]];
	if ([[NSFileManager defaultManager] fileExistsAtPath:finalPath]) {
		NSLog(@"dict appconfig init from file");
		
		propDict =  [[NSMutableDictionary alloc] initWithContentsOfFile:finalPath];
		return NO;
		
	}
	else {
		NSLog(@"create appconfig new dictionary ");
		propDict =  [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"",@"user-name",
									  @"",@"user-auth-code",
									  @"http://mybuddies.emiu.net", @"server-url",
									  @"avatar.png", @"user-avatar",
									  nil ];	
		return YES;
	}
	


	
}


+ (NSString *) getDocumentFolder {
	
	NSString *docpath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
	return docpath;
	
}

-(NSString *) getConfigFile {
    NSString *configfile = [[AppConfig getDocumentFolder] stringByAppendingPathComponent:@"config.plist"];
	return configfile;
}



- (NSString*) getProperty:(NSString *) key { 
	
	if (!propDict)
		[self firstTime];
	
	// Read property
	NSString *val = [propDict objectForKey:key ];
	return val;

}

-(void) setProperty:(NSString *) key setValueTo:(NSString *) val {
	// check if key exists

	if (!propDict)
		[self firstTime];
	
	NSLog(@"AppConfig.m set property call");
	if ([propDict objectForKey:key]!=nil) {
		// delete record
		[propDict removeObjectForKey:key];
	}
	
	[propDict setObject:val forKey:key];
	
	// get application bundle
	NSString *path = [[NSBundle mainBundle] bundlePath];
	NSLog(@"bundle path is %@", path);
	// locate directory of file structure
	NSString *finalPath = [NSString stringWithString:[self getConfigFile]];
						   
	NSLog(@"saved file folder: %@", finalPath);
	[propDict writeToFile:finalPath  atomically:YES];

		
}

-(void) dealloc {
	[propDict release];
	[super dealloc];
}


@end
